#include "rel.h"

// Arrays to store messages and the file name
char receiveMessageBuffer [MSG_LEN];
char sendMessageBuffer [MSG_LEN];
char fileName [FILENAME_LEN];

// Sequence number and file name length
unsigned long long currentSequenceNumber;
int fileNameLength;

// Toggles debugging on or off
int debug = false;

// Stopwatch
time_t start;

// Declares sender as flag = 1;
int sender = true;

// Socket file descriptor
int socketfd;

// Stores Port Number receiver binds on.  If this is the sender, then this
// is the port number of the receiver
unsigned short receiverPort;

// Receiver's ipAddress
char ipAddress[20];

// Stores port information for Sender
unsigned short senderPort;

// Timestamp of last response from other application
time_t lastResponseTime = 2147483647;

// Size of Message in Send Buffer
int sendMessageSize = 0;

// Size of Message in Receive Buffer
int receiveMessageSize = 0;

// Number of Retransmissions
int numRetransmits = 0;

// Mutex Lock
pthread_mutex_t mutexLock = PTHREAD_MUTEX_INITIALIZER;

// Turn off timer
int timerOn = true;

// Boolean to test if transmission successful
int successfulTransfer = false;

main (char argc, char * argv[]){
  
  // CommandLine Arguments
  commandLineSend(argc, argv, fileName, ipAddress, &receiverPort);

  // Configure Sender for sending/receiving over network
  socketfd = networkConfigure(0);
	
  // Declare initial sequence number
  currentSequenceNumber = 0;	
  
  // Declare initial file name length
  fileNameLength = 0;
  
  // can we use strlen(fileName) instead?
  
  for (fileNameLength; fileNameLength < FILENAME_LEN; fileNameLength++) {
    if (fileName[fileNameLength] == '\x00') {
      break;
    }
  }// end for

  struct sockaddr sa;
  struct addressPort ap;
  
  // Create thread to keep track of responses
  createTimerThread();
  
  // number of bytes received through network
  int bytesReceived;
  
  // send test
  int testNumber = 0;
  if (debug){
  	puts("creating initial message.");
  }
  
  sendMessageSize = fileStatusCreation(0);
  sendUDP(ipAddress, receiverPort, socketfd, sendMessageBuffer, sendMessageSize);  


  
  // Wait to receive message
  while(true){
  	if (debug)
    	printf("\nWaiting to Receive from Receiver...\n");
    
    // Call Recvfrom to wait for incoming messages from receiver
    bytesReceived = receiveUDP (socketfd, (unsigned char *) receiveMessageBuffer, MSG_LEN, &sa);
    
    // Message will be loaded into receiveMessageBuffer
    if (debug){
      printf("Sending #%d\n", testNumber++);
      printf("Bytes Received: %d", bytesReceived);
      printMessage(receiveMessageBuffer, bytesReceived);
    }  
    
    // Assign receiver's address and port to global ipAddress and port variables
    getAddressPort(&sa, &ap );
    parseMessage();
		sendUDP(ipAddress, receiverPort, socketfd, sendMessageBuffer, sendMessageSize);  

  }

}